from celery import Celery,shared_task
from django.db import transaction
from django.utils import timezone
from datetime import timedelta

from gi.overrides.Gtk import stock_lookup

from order import models
from sku import models as sku_models

@shared_task
def celery_check_order():
    """
    :return: 每分钟检查一次订单状态，如果订单状态为待支付，并且超过10分钟，那么就将订单状态改为已取消
    """
    # 获取10分钟前的时间
    current_time = timezone.now()- timedelta(minutes=10)
    print('执行一次')
    # 开启事务
    with transaction.atomic():
        order_query_set=models.Order.objects.filter(order_of_payment=1,created_time__lte=current_time)
        stock_lookup_queryset=models.OrderStockLock.objects.filter(order__in=order_query_set)
        for stock_lookup in stock_lookup_queryset:
            sku=stock_lookup.sku
            # 解锁锁定的数量
            sku.frozen_stock-=stock_lookup.quantity
            sku.save()
        stock_lookup_queryset.delete()
        # 将这些订单标记为已取消
        order_query_set.delete()